package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserlocationApiImpl implements UserlocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新地理位置
     *
     * @param userId
     * @param latitude
     * @param longitude
     * @param addrStr
     * @return
     */
    @Override
    public Boolean updateLocation(Long userId, Double latitude, Double longitude, String addrStr) {
        try {
            //根据用户id去查询位置表中是否有数据
            Query query = Query.query(Criteria.where("userId").is(userId));
            UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
            if (location == null) {
                //如果没有，则保存
                location = new UserLocation();
                location.setUserId(userId);
                location.setLocation(new GeoJsonPoint(longitude, latitude));
                location.setAddress(addrStr);
                location.setCreated(System.currentTimeMillis());
                location.setUpdated(System.currentTimeMillis());
                location.setLastUpdated(System.currentTimeMillis());
                mongoTemplate.save(location);
            } else {
                //如果有，则更新
                Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                        .set("address",addrStr)
                        .set("updated", System.currentTimeMillis())
                        .set("lastUpdated", location.getUpdated());
                mongoTemplate.updateFirst(query, update, UserLocation.class);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 查询附近的人的所有用户ID
     * @param userId
     * @param metre：距离，也就是半径，默认单位为m
     * @return
     */
    @Override
    public List<Long> findNearUser(Long userId, Double metre) {
        //根据当前用户id，查询位置
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        if(location==null){
            return null;
        }
        //用当前用户的位置绘制出圆心点
        GeoJsonPoint point = location.getLocation();
        //绘制半径
        Distance distance = new Distance(metre/1000, Metrics.KILOMETERS);
        //根据圆心点和半径绘制圆形
        Circle circle = new Circle(point,distance);
        //查询坐标位置在圆中的用户信息
        Query locationQuery = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> result = mongoTemplate.find(locationQuery, UserLocation.class);

        return CollUtil.getFieldValues(result,"userId",Long.class);
    }
}
